<template>
  <div class="create">
    <h2>{{ $route.params.id ? "编辑" : "创建" }}新闻</h2>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="简介">
        <el-input v-model="form.intro"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <vue-editor
          id="editor"
          useCustomImageHandler
          @imageAdded="handleImageAdded"
          v-model="form.content"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{
          $route.params.id ? "修改保存" : "立即创建"
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";

export default {
  components: {
    VueEditor,
  },
  data() {
    return {
      form: {
        id: "",
        content: "",
      },
    };
  },
  methods: {
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {

      var formData = new FormData();
      formData.append("file", file);

      const res = await this.$$http.post("upload", formData);
      let url = res.data.url; // Get url from response
      Editor.insertEmbed(cursorLocation, "image", url);
      resetUploader();
      
    },
    async onSubmit() {
      console.log("submit!");
      let url = this.form.id == "" ? "common/news" : "common/news/edit";
      const res = await this.$http.post(url, this.form);
      console.log(res);

      this.$message({
        type: "success",
        message: this.form.id == "" ? "创建成功!" : "修改成功",
      });

      this.form = {
        id: "",
        name: "",
        parent: null,
      };
    },
    async getItem(id) {
      const res = await this.$http.get(`common/news/${id}`);
      this.form = res.data;
    },
  },
  created() {
    this.$route.params.id && this.getItem(this.$route.params.id);
  },
  mounted() {},
};
</script>

<style lang="css">
@import "~vue2-editor/dist/vue2-editor.css";

/* Import the Quill styles you want */
@import "~quill/dist/quill.core.css";
@import "~quill/dist/quill.bubble.css";
@import "~quill/dist/quill.snow.css";
</style>